import { PlusOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, message, Modal } from 'antd';
import type { SorterResult } from 'antd/es/table/interface';
import React, { useRef, useState } from 'react';
import AddStaggerConfig from './components/addLogisticsConfig';
import UpadteStaggerConfig from './components/updateLogisticsConfig';
import type { ListLogisticsType } from './data.d';
import { handleLogisticsConfig, logisticsConfigPages } from './service';
import { useModel } from 'umi';
import PlaceHolderCpn from '@/components/PlaceHolderCpn';
import { Auths } from '@/utils/typings.d';
// import AdvancePayment from '@/pages/ParkingOrder/components/AdcancePayment';
// import styles from './style.less';

const LogisticsTableList: React.FC<ListLogisticsType> = () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const auths = currUser?.auth ? new Set(currUser.auth.logistics || []) : new Set();
  const ifCreate = auths.has(Auths.CREATE);
  const ifModify = auths.has(Auths.MODIFY);
  const ifDelete = auths.has(Auths.DELETE);
  const [sorter, setSorter] = useState<string>('');
  const actionRef = useRef<ActionType>();
  const [addConfigVisible, setAddConfigVisible] = useState<boolean>(false);
  const [updateConfigVisible, setUpdateConfigVisible] = useState<boolean>(false);
  const [clickUpdateId, setClickUpdateId] = useState<string>('');

  const columns: ProColumns<ListLogisticsType>[] = [
    {
      title: '物流名称',
      dataIndex: 'logisticsName',
      hideInSearch: false,
      ellipsis: true,
    },
    {
      title: '起步重量(kg)',
      dataIndex: 'startingWeight',
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '重量区间(kg)',
      dataIndex: 'weightInterval',
      hideInSearch: true,
      ellipsis: true,
      render: (_, record) => {
        let showInterval = `${record?.startingWeight}`;
        for (let i = 0; i < record.weightInterval?.length; i++) {
          showInterval =
            showInterval + `-${record?.weightInterval[i]} | ${record?.weightInterval[i]}`;
        }
        return showInterval + '-∞';
      },
    },
    {
      title: '重量进位规则',
      dataIndex: 'weightRules',
      hideInSearch: true,
      ellipsis: true,
      valueEnum: {
        3: { text: '进位至下一个0.5kg' },
        2: { text: '四舍五入取整数' },
        1: { text: '无规则' },
      },
    },
    {
      title: '运费进位规则',
      dataIndex: 'shippingRules',
      ellipsis: true,
      hideInSearch: true,
      valueEnum: {
        2: { text: '四舍五入取整数' },
        1: { text: '无规则' },
      },
    },
    {
      title: '收费方式',
      dataIndex: 'chargeWay',
      ellipsis: true,
      hideInSearch: true,
      valueEnum: {
        2: { text: '对段加首重' },
        1: { text: '分段收费' },
      },
    },
    {
      title: '是否有最低收费',
      ellipsis: true,
      dataIndex: 'chargeType',
      hideInSearch: true,
      valueEnum: {
        2: { text: '有最低收费' },
        1: { text: '没有最低收费' },
      },
    },
    {
      title: '省内打折（折）',
      ellipsis: true,
      dataIndex: 'provinceDiscount',
      hideInSearch: true,
    },
    {
      title: '省外打折（折）',
      dataIndex: 'outsideDiscount',
      ellipsis: true,
      hideInSearch: true,
    },
    {
      title: '操作',
      hideInSearch: true,
      valueType: 'option',
      render: (_, record) => {
        const onClickExitPark = () => {
          Modal.confirm({
            title: `是否要删除${record.logisticsName}的物流配置`,
            content: (
              <>
                <p></p>
                <p>删除之后无法撤回，请谨慎操作！</p>
              </>
            ),
            okText: '确定',
            cancelText: '取消',
            onOk: async () => {
              const hide = message.loading('正在删除');
              const res = await handleLogisticsConfig(record._id);

              hide();
              if (res === true) {
                message.success(`删除成功`);
                actionRef.current?.reload();
                return true;
              } else {
                message.error(`删除失败,${res.message}`);
                return false;
              }
            },
            centered: true,
            width: '300px',
            style: { height: '15vw' },
          });
        };
        return ifDelete || ifModify
          ? [
              ifModify && (
                <a
                  onClick={() => {
                    setUpdateConfigVisible(true);
                    setClickUpdateId(record._id);
                  }}
                >
                  修改
                </a>
              ),
              ifDelete && <a onClick={onClickExitPark}>删除</a>,
            ]
          : [<PlaceHolderCpn key={record._id} />];
      },
    },
  ];

  return (
    <PageHeaderWrapper>
      <ProTable<ListLogisticsType>
        scroll={{ x: true }}
        actionRef={actionRef}
        rowKey="id"
        onChange={(_, _filter, _sorter) => {
          const sorterResult = _sorter as SorterResult<ListLogisticsType>;
          if (sorterResult.field) {
            setSorter(`${sorterResult.field}_${sorterResult.order}`);
          }
        }}
        toolBarRender={() => [
          ifCreate && (
            <Button
              key="button"
              icon={<PlusOutlined />}
              type="primary"
              onClick={() => {
                setAddConfigVisible(true);
              }}
            >
              添加
            </Button>
          ),
        ]}
        params={{
          sorter,
        }}
        tableAlertRender={() => false}
        request={async (params = {}) => {
          const { current: page, pageSize, logisticsName, ...filter } = params;
          const res = await logisticsConfigPages({
            page,
            pageSize,
            ...filter,
            logisticsName: logisticsName,
          });
          return res;
        }}
        columns={columns}
        rowSelection={false}
        pagination={{
          defaultPageSize: 10, //每页显示的数量
          size: 'default', //页数显示的样式
          showQuickJumper: true, //默认显示，两页以上才显示，跳转到指定页数
          showSizeChanger: true,
        }} //默认显示，多页以上才显示，让每页显示指定数据量的数据
      />
      {updateConfigVisible && (
        <UpadteStaggerConfig
          visible={updateConfigVisible}
          unVisible={() => {
            setUpdateConfigVisible(false);
            setClickUpdateId('');
          }}
          id={clickUpdateId}
          reloadFunc={() => actionRef.current?.reload()}
        />
      )}
      {addConfigVisible && (
        <AddStaggerConfig
          visible={addConfigVisible}
          unVisible={() => setAddConfigVisible(false)}
          reloadFunc={() => actionRef.current?.reload()}
        />
      )}
    </PageHeaderWrapper>
  );
};

export default LogisticsTableList;
